package com.zxb.core.util;

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Random;

public class NumericalExpUtil {
    private static final String OPERATORS = "+-";
    private static final String EQUALS = "=?";
    private static final String NUMBERS = "0123456789";
    private static final int CODE_LENGTH = 2;
    private static final Random RANDOM = new Random();

    public static String generateVerificationCode() {
        StringBuilder codeBuilder = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH - 1; i++) {
            int numberIndex = RANDOM.nextInt(NUMBERS.length());
            char operator = OPERATORS.charAt(RANDOM.nextInt(OPERATORS.length()));
            codeBuilder.append(NUMBERS.charAt(numberIndex));
            codeBuilder.append(operator);
        }
        int lastNumberIndex = RANDOM.nextInt(NUMBERS.length());
        codeBuilder.append(NUMBERS.charAt(lastNumberIndex));
        return codeBuilder.toString();
    }

    public static String[] getVerificationCode() throws ScriptException {
        String verificationCode = generateVerificationCode();
        final String calculateResult = calculateResult(verificationCode);
        return new String[]{verificationCode + EQUALS, calculateResult};
    }

    private static String calculateResult(String verificationCode) throws ScriptException {
        StringBuilder expressionBuilder = new StringBuilder();
        for (int i = 0; i < verificationCode.length(); i++) {
            expressionBuilder.append(verificationCode.charAt(i));
        }
        return new ScriptEngineManager()
                .getEngineByName("JavaScript")
                .eval(expressionBuilder.toString())
                .toString();
    }
}
